package com.schoolCommunity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.schoolCommunity.entity.Admin;
import com.schoolCommunity.entity.Information;
import com.schoolCommunity.entity.Member;
import com.schoolCommunity.mapper.AdminMapper;
import com.schoolCommunity.mapper.MemberMapper;
import com.schoolCommunity.service.AdminService;
import com.schoolCommunity.util.DeleteES;
import com.schoolCommunity.util.InsertES;
import com.schoolCommunity.util.SearchES;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import com.schoolCommunity.service.MemberService;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@SpringBootTest
public class test {

    @Autowired
    private MemberService MemberService;
    @Resource
    private MemberMapper memberMapper;
    @Autowired
    private AdminService adminService;
    @Resource
    private AdminMapper adminMapper;
    @Autowired
    private SearchES searchES;
    @Autowired
    private InsertES insertES;
    @Autowired
    private DeleteES deleteES;

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;


    //批量添加测试用户
    @Test
    void addMember() {

        int c = 0;

        for (int i = 1; i <11 ; i++) {
        Member member = new Member();
        member.setPassword("123456").setEmail("体育美"+i+"@qq.com").setNickname("体美用户"+i+"昵称")
                .setGrade(2017).setCollege("体美学院").setFamilyName("体美")
                .setSex(0);

            Information information = MemberService.InsertMember(member);
            System.out.println(information);
            c++;

        }
        System.out.println(c+"条测试用户插入成功");

    }


    //测试分页查询
    @Test
    void mytest() {
        Page<Member> page = new Page<>(509, 20);
        memberMapper.selectPage(page, null);
        List<Member> records = page.getRecords();
        records.forEach(System.out::println);
        long total = page.getTotal();
        System.out.println("一共有" + total + "条数据");

    }

    //添加需要的索引
    @Test
    void AddIndex() throws IOException {

        //添加member表索引
        //1、创建索引请求
//        CreateIndexRequest request = new CreateIndexRequest("member");
//        CreateIndexRequest request = new CreateIndexRequest("admin");
//        CreateIndexRequest request = new CreateIndexRequest("confession_wall_message");
        CreateIndexRequest request = new CreateIndexRequest("confession_wall");
//        CreateIndexRequest request = new CreateIndexRequest("for_index");
//        CreateIndexRequest request = new CreateIndexRequest("for_index_message");
//        CreateIndexRequest request = new CreateIndexRequest("commodity_transaction");
//        CreateIndexRequest request = new CreateIndexRequest("commodity");
        //2、客户端执行请求 IndicesClient，请求后获得相应
        CreateIndexResponse createIndexResponse =
                client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);

    }

    //测试添加文档
    @Test
    void testAddDoc() throws IOException {
//        创建member对象

        List<Member> memberList = new ArrayList<>();

        memberList = memberMapper.selectList(null);


        for (Member member : memberList) {

//            insertES.InsertMember(member);

//            测试删除
            System.out.println(deleteES.DeleteESMember(member.getId()));


//            //创建请求
//            IndexRequest request = new IndexRequest("admin");
//
//            //规则  PUT /yth_index/_doc/1
//            //不设置id则产生随机id
////        request.id("1");
//            //设置超时
//            request.timeout(TimeValue.timeValueSeconds(1));
//
//            //将数据放入请求json ,需要引入fastJson
//            request.source(JSON.toJSONString(admin), XContentType.JSON);
//
//            //客户端发送请求
//            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
//
//            System.out.println(response.toString());
//            System.out.println(response.status());  //对应命令返回的状态 CREATED


        }


    }

    //测试获取文档
    //搜索文档
    @Test
    void testGetExists() throws IOException {
        GetRequest yth_index = new GetRequest("member_index", "1");
        GetResponse response = client.get(yth_index, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());  //打印文档内容
        System.out.println(response); //打印所有返回信息
    }

    //搜索数据
//参数：1、搜索关键词。2、搜索分页起始页数。3、每页数量
    @Test
//    public List<Map<String,Object>> searchPage(String keyword,int pageNo,int pageSize) throws IOException {
    public void searchPage() throws IOException {

        String keyword = "3";
        int pageNo = 1;
        int pageSize = 200;

        if (pageNo <= 1) {
            pageNo = 1;
        }

        //条件搜索
        //搜索的索引
        SearchRequest searchRequest = new SearchRequest("member");
        //创建搜索条件构造器
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //设置分页
        //开始页数
        searchSourceBuilder.from(pageNo);
        //每页数量
        searchSourceBuilder.size(pageSize);

//        设置精确匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("nickname", keyword);

//        //设置拆分匹配
//        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //执行搜索
        searchRequest.source(searchSourceBuilder);
        //获取搜索结果
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit documentFields : searchResponse.getHits().getHits()) {
            list.add(documentFields.getSourceAsMap());
        }
//        return list;
        list.forEach(System.out::println);
    }

    //搜索数据
//参数：1、搜索关键词。2、搜索分页起始页数。3、每页数量
    @Test
    public void searchNewPage() throws IOException {

        //条件搜索
        //搜索的索引
        SearchRequest searchRequest = new SearchRequest("member");
        //创建搜索条件构造器
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //构建查询条件
        searchSourceBuilder.query(QueryBuilders.boolQuery()
                //匹配查询条件
                .must(QueryBuilders.matchQuery("nickname", "美术"))
                //可以设置多条匹配
                .must(QueryBuilders.matchQuery("familyName", "97"))

        )
                //设置分页查询，从0开始，查20条
                .from(0).size(20);

        //执行搜索
        searchRequest.source(searchSourceBuilder);
        //获取搜索结果
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果
        List<Map<String, Object>> list = new ArrayList<>();
        System.out.println(searchResponse.getHits().getHits().length);
        for (SearchHit documentFields : searchResponse.getHits().getHits()) {
            //获取key名字
//            System.out.println(documentFields.getSourceAsMap().keySet());
            list.add(documentFields.getSourceAsMap());

//            Iterator<String> iterator = documentFields.getSourceAsMap().keySet().iterator();
//            while(iterator.hasNext()){
//                System.out.println(iterator.next());
//            }

//            转化为对象
//            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
//            Object jsonO = JSONArray.toJSON(sourceAsMap);
//            String json = jsonO.toString();
//            Member member = JSONArray.parseObject(json, Member.class);
//            System.out.println(member);


        }
        list.forEach(System.out::println);

    }

    //测试搜索工具类
    @Test
    public void testSearch() throws IOException {
        List<Member> memberList = searchES.searchMember(null, "12", 1);
        memberList.forEach(System.out::println);
    }


}
